﻿using AutoMapper;
using B.S.GridManage.Api.Write.Application.Command.GridTeam;
using B.S.GridManage.Domain.Entities;
using B.S.GridManage.ErrorCode;
using B.S.GridManage.Infrastructure.Interface;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.GridManage.Api.Write.Application.Handler.GridTeam
{
    public class AddGridTeamHandler : IRequestHandler<AddGridTeamCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<GridTeamModel> teamRepo;
        private readonly IMapper mapper;

        public AddGridTeamHandler(IBaseRepository<GridTeamModel> teamRepo, IMapper mapper)
        {
            this.teamRepo = teamRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 添加网格队伍的方法
        /// </summary>
        /// <param name="request">请求命令</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddGridTeamCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            var model = mapper.Map<GridTeamModel>(request);
            model.Id = YitIdHelper.NextId();

            var r =await teamRepo.CreateAsync(model);
             
            if (r > 0)
            {
                res.Msg = "添加网格队伍成功!";
                res.Code = ApiEnum.Success;
                res.Data = r;
            }
            else
            {
                res.Msg = "添加网格队伍失败!";
                res.Code = ApiEnum.Failed;
                res.Data = r;
            }

            return res;
        }
    }
}
